package com.jxpanda.starter.wechat.pojo;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.jxpanda.commons.constant.StringConstant;
import com.jxpanda.commons.encrypt.RSA;
import com.jxpanda.commons.toolkit.json.JsonKit;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * @author Panda
 */
@Data
@NoArgsConstructor
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
public class WechatResponse {

    @JsonProperty("errcode")
    private Integer errCode = 0;
    @JsonProperty("errmsg")
    private String errMsg = StringConstant.BLANK;

    /**
     * 根据微信的文档，返回值为0的话就说明成功了
     * 我喜欢用effective这个单词，标明这个对象是有效的
     */
    public boolean isEffective() {
        return errCode == 0;
    }

    @Data
    @EqualsAndHashCode(callSuper = true)
    public static class AccessToken extends WechatResponse {
        @JsonProperty("access_token")
        private String accessToken = StringConstant.BLANK;
        @JsonProperty("expires_in")
        private Long expiresIn = 0L;
    }

    @Data
    @EqualsAndHashCode(callSuper = true)
    public static class Session extends WechatResponse {
        @JsonProperty("openid")
        private String openId = StringConstant.BLANK;
        @JsonProperty("session_key")
        private String sessionKey = StringConstant.BLANK;
        @JsonProperty("unionid")
        private String unionId = StringConstant.BLANK;

        public String encrypt() {
            return RSASingleton.INSTANCE.RSA.encrypt(JsonKit.toJson(this));
        }

        public static Session decrypt(String encryptedSession) {
            return JsonKit.fromJson(RSASingleton.INSTANCE.RSA.decrypt(encryptedSession), Session.class);
        }

        private enum RSASingleton {
            INSTANCE;
            private final RSA RSA = new RSA();
        }

    }


    @Data
    @EqualsAndHashCode(callSuper = true)
    public static class QRCode extends WechatResponse {
        @JsonProperty("contentType")
        private String contentType;
        @JsonProperty("buffer")
        private String buffer;
    }


}
